package com.sunwayhorizo.health.common;

import java.util.*;
import javax.validation.*;

import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.dto.ResultsDTO;

@Name("ValidateUtil")
public class ValidateUtil implements ValidateUtilLocal {

	private Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	@Override
	public <T> boolean verified(T t, Class<?>... groups) {
		return getConstraintViolations(t, groups).isEmpty();
	}

	@Override
	public <T> Set<ConstraintViolation<T>> getConstraintViolations(T t,
			Class<?>... groups) {
		return validator.validate(t, groups);
	}

	public void setValidator(Validator validator) {
		this.validator = validator;
	}

	public Validator getValidator() {
		return validator;
	}

	@Override
	public <T> void verifiedThrowsException(T t, Class<?>... groups)
			throws ValidationException {
		Set<ConstraintViolation<T>> cs = validator.validate(t, groups);

		if (!cs.isEmpty()) {
			StringBuilder sb = new StringBuilder();

			for (ConstraintViolation<T> c : cs) {
				sb.append(c.getMessage() + "\n");
			}

			throw new ValidationException(sb.toString());
		}
	}

	@Override
	public <T> ResultsDTO verifiedReturnResultsDTO(T t, Class<?>... groups) {
		Set<ConstraintViolation<T>> cs = validator.validate(t, groups);

		if (!cs.isEmpty()) {
			StringBuilder sb = new StringBuilder();

			for (ConstraintViolation<T> c : cs) {
				sb.append(c.getMessage() + "\n");
			}
			
			return new ResultsDTO(true, false, sb.toString());
		}
		return null;
	}

}
